package com.wjjun.base.ui.activity

import android.view.View
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.wjjun.base.BR
import com.wjjun.base.ui.listener.ActivityPresenter
import com.wjjun.base.ui.viewmodel.BaseActivityViewModel
import com.wjjun.base.utils.ViewModelFactory

/**
 * 基础绑定Activity,只实现了绑定功能
 * author : wangjunjun
 * date   : 2022/5/31
 * desc   :
 */
abstract class BaseBindingActivity<VM : BaseActivityViewModel, VD : ViewDataBinding> :
    BaseActivity(), ActivityPresenter {

    lateinit var viewModel: VM

    lateinit var viewDataBinding: VD

    override fun initViews() {
        buildViewModel()
        buildViewBinding()
        bindViewModel()
    }

    open fun buildViewModel() {
        //从ViewModelProvider中获取的ViewModel可以实现hilt注入，且会在Activity重启时还原
        viewModel = ViewModelFactory.createViewModel(
            this,
            this.javaClass,
            BaseActivityViewModel::class.java
        )
    }

    open fun buildViewBinding() {
        var layoutId = getLayoutId()
        if (layoutId == 0) {
            layoutId = viewModel.getLayoutId()
        }
        viewDataBinding = DataBindingUtil.setContentView(this, layoutId)
        viewDataBinding.lifecycleOwner = this
    }

    @LayoutRes
    open fun getLayoutId(): Int {
        return 0
    }

    open fun bindViewModel() {
        bindData(BR.viewModel, viewModel)
        bindListener(BR.listener, this)

    }

    /**
     * 绑定布局中的数据
     * @param variableId: 对应布局文件中variable标签的name属性
     */

    open fun bindData(variableId:Int, data: Any){
        viewDataBinding.setVariable(variableId, data)
    }

    /**
     * 绑定布局中的事件
     * @param variableId: 对应布局文件中variable标签的name属性
     */
    open fun bindListener(variableId:Int, listener: Any){
        viewDataBinding.setVariable(variableId, listener)
    }

    fun setTitle(title: String) {
        viewModel.setTitle(title)
    }

    override fun onLeftIconClick(view: View) {
        finish()
    }

    override fun onTitleClick(view: View) {
    }

    override fun onSubTitleClick(view: View) {
    }

    override fun onRightIconClick(view: View) {
    }

    override fun onRightTxtClick(view: View) {
    }

    override fun onPointerCaptureChanged(hasCapture: Boolean) {}
}

